Ext.require(['*']);

//每一个列都会出现鼠标悬浮上去显示内容
/** 
 * //适用于Extjs4.x
* @class Ext.grid.GridView 
* @override Ext.grid.GridView 
* GridPanel单元格不能选中复制问题 
* 单元格数据显示不完整 ,增加title 浮动提示信息 
*/ 
Ext.override(Ext.grid.GridPanel, {
  afterRender : Ext.Function.createSequence(Ext.grid.GridPanel.prototype.afterRender,
      function() {
          /* 默认显示提示
          if (!this.cellTip) {
              return;
          }*/
          
          var view = this.getView();
          
          this.tip = new Ext.ToolTip({
              target: view.el,
              delegate : '.x-grid-cell-inner',
              trackMouse: true, 
              renderTo: Ext.getBody(),  
              listeners: {  
                  beforeshow: function updateTipBody(tip) {
                      //取cell的值
                      //fireFox  tip.triggerElement.textContent
                      //IE  tip.triggerElement.innerText 
                      var tipText = (tip.triggerElement.innerText || tip.triggerElement.textContent);
                      if (Ext.isEmpty(tipText) || Ext.isEmpty(tipText.trim()) ) {
                          return false;
                      }
                      
                      tip.update(tipText);
                  }
              }
          });
      })
});

//获取用户登录信息
function getUserSession(){
  Ext.Ajax.request({
      url: '/admin_user/session',
      method : 'GET',
      success: function(response, opts) {
          var jsonResult = Ext.JSON.decode(response.responseText);
          if(!jsonResult || !jsonResult.success || !jsonResult.user_name)
          {
            Ext.Msg.alert('信息提示', '您还未登录！',function(){
              window.location = '/admin/login.html';
            });   
          } else {
            return jsonResult;
          }
      },
      failure: function(response, opts) {
        Ext.Msg.alert('信息提示', '您还未登录或Session已失效，请重新登录！',function(){
          window.location = '/admin/login.html';
        });         
      }
  });
}

//判断字符串是否以指定字符结尾
String.prototype.endWith=function(endStr){
  var d=this.length-endStr.length;
  return (d>=0&&this.lastIndexOf(endStr)==d)
}

Date.prototype.format = function(fmt) {
 var o = {
     "M+": this.getMonth() + 1,
     //月份
     "d+": this.getDate(),
     //日
     "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
     //小时
     "H+": this.getHours(),
     //小时
     "m+": this.getMinutes(),
     //分
     "s+": this.getSeconds(),
     //秒
     "q+": Math.floor((this.getMonth() + 3) / 3),
     //季度
     "S": this.getMilliseconds() //毫秒
 };
 var week = {
     "0": "\u65e5",
     "1": "\u4e00",
     "2": "\u4e8c",
     "3": "\u4e09",
     "4": "\u56db",
     "5": "\u4e94",
     "6": "\u516d"
 };
 if (/(y+)/.test(fmt)) {
     fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 }
 if (/(E+)/.test(fmt)) {
     fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f": "\u5468") : "") + week[this.getDay() + ""]);
 }
 for (var k in o) {
     if (new RegExp("(" + k + ")").test(fmt)) {
         fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
     }
 }
 return fmt;
}

/**
 * 刷新树
 * @param {} url 数据请求地址
 * @param {} tree 树
 */
function refreshResTree(url, tree){
	var cateTreeRoot = {
		text:'根节点',
		id:0,
	    expanded: true,
	    children: []
	}
	Ext.Ajax.request({
        url: url,
        method : 'GET',
        success: function(response, opts) {
            //设置root
            cateTreeRoot.children = Ext.JSON.decode(response.responseText);
            //刷新资源树
    		    tree.setRootNode(cateTreeRoot);
        },
        failure: function(response, opts) {
        	var data = eval("("+response.responseText+")");
        	if(!data.success){
        		Ext.Msg.alert('信息提示',data.msg);
        	} else {
        		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
        	}
        }
    });
}

/**
 * 获取当前节点的所有父节点id组成的数组
 * @param {} node
 */
var parentNodeIdAry = new Array();
function getAllParentNode(node) {
	if(node) {
		var nodeId = node.get('id');
		if( node.parentNode!=null){
			getAllParentNode(node.parentNode);
		}
		parentNodeIdAry.push(nodeId);
	}
}

/**
 * 计算加载表单排序规则
 * @param {} type
 * @param {} form
 */
function loadSort(type, form, store) {
	var count = 1;
	if(type == 'add') {
		count = store.getTotalCount() + 1;
	} else {
		count = store.getTotalCount();
	}
	var sort_data = [];
	for(var i=1;i<=count;i++) {
		sort_data.push({'num':i,'num':i});
	}
	Ext.getCmp('sorder').getStore().loadData(sort_data);
}

function showDictValue(store, val){
	if(val) {
        var str = val;
        for(var i=0;i<store.getCount();i++){  
            var recored = store.getAt(i);  
            if(recored.get('dict_key') == val){
                str = recored.get('dict_value');
                break;
            }
        }
        //console.log(str);
        return str;  
    } else {
    	return '';
    }
}

function showCityName(store, val){
	if(val) {
        var str = val;
        for(var i=0;i<store.getCount();i++){  
            var recored = store.getAt(i);  
            if(recored.get('city_id') == val){
                str = recored.get('city_name');
                break;
            }
        }
        return str;  
    } else {
    	return '';
    }
}

function showAreaName(store, val){
    if(val) {
        var str = val;
        for(var i=0;i<store.getCount();i++){  
            var recored = store.getAt(i);  
            if(recored.get('area_id') == val){
                str = recored.get('area_name');
                break;
            }
        }
        return str;  
    } else {
        return '';
    }
}

function showUserName(store, val){
    if(val) {
        var str = val;
        for(var i=0;i<store.getCount();i++){  
            var recored = store.getAt(i);  
            if(recored.get('user_id') == val){
                str = recored.get('user_realname');
                break;
            }
        }
        return str;  
    } else {
        return '';
    }
}

function showMultiUserName(store, val, separator){
    if(val) {
        var str='';
        var ary = new String(val).split(separator);
        for(k=0;k<ary.length;k++){
            var user_id = ary[k];
            for(var i=0;i<store.getCount();i++){  
                var recored = store.getAt(i);  
                if(parseInt(recored.get('user_id')) == parseInt(user_id)){
                    str += (recored.get('user_realname')+',');
                }
            }
        }
        if(str){
            if(str.endWith(',')){
                str = str.substring(0,str.length-1);
            }
        }
        return str;  
    } else {
        return '';
    }
}

//显示iframe弹窗
function doAdd(url,title,width,height){
    showHandlerWin(url,title,width,height);
}
function showHandlerWin(url,title,width,height){
    if(typeof(width) == 'undefined'){
        width = 1100;
    }
    if(typeof(height) == 'undefined'){
        height = 625;
    }
    win = null;
    if (!win) {
        win = new Ext.Window({
            title: title,
            header: {
                titlePosition: 2,
                titleAlign: 'center'
            },
            closable: true,
            closeAction: 'hide',
            x : 0,
            y : 0,
            width: width,
            height: height,
            html : '<iframe width="100%" height="100%" frameborder="0" src="' + url + '"></iframe>'
        });
    }
    win.show();
}

function refreshDeptTree(url, tree){
	var cateTreeRoot = {
		text:'学校',
		id:0,
	    expanded: true,
	    children: []
	}
	Ext.Ajax.request({
        url: url,
        method : 'GET',
        success: function(response, opts) {
            //设置root
            cateTreeRoot.children = Ext.JSON.decode(response.responseText);
            //刷新资源树
    		    tree.setRootNode(cateTreeRoot);
        },
        failure: function(response, opts) {
        	var data = eval("("+response.responseText+")");
        	if(!data.success){
        		Ext.Msg.alert('信息提示',data.msg);
        	} else {
        		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
        	}
        }
    });
}